<template>
  <section class="author">
        <article class="item">
            <h1 class="about-logo">
                <!-- <img src="images/boblog.png" alt="logo"> -->
                <span style="font-family: fantasy;font-weight:400;font-size:36px;
                color: #edc940;">FITBLOG</span>
            </h1>
        </article>
        <Form :model="formData" :label-width="80" >
            <FormItem label="昵称：">
                <Input v-model="formData.nickname" :readonly="userid !== formData.id" placeholder="Enter something..." class="ipt"></Input>
            </FormItem>
            <FormItem label="头像：">
            <Upload
                ref="upload"
                :show-upload-list="false"
                :default-file-list="defaultList"
                :on-success="uploadSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="2048"
                v-if="userid === formData.id"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                multiple
                type="drag"
                action="http://localhost:3000/api/v1/upload"
                style="display: inline-block;width:70px;">
                <div style="width: 70px;height:70px;line-height: 70px;">
                <img :src="formData.img || 'http://127.0.0.1:3000/upload/touxiang.png'" alt="" style="width:100%;height: 100%;">
                    <!-- <Icon type="ios-camera" size="20"></Icon> -->
                </div>
            </Upload>
            <img :src="formData.img || 'http://127.0.0.1:3000/upload/touxiang.png'" v-else alt="" style="width:70px">
            </FormItem>
            <FormItem label="邮箱：" >
                <Input v-model="formData.mail" type="email" placeholder="Enter something..." class="ipt" @on-change="checkMail" :readonly="userid !== formData.id"></Input>
                <span style="color:red;margin-left:5px" v-if="show">请输入合法的邮箱</span>
            </FormItem>
            <FormItem label="身份：">
                <p>{{formData.is_student === '0' ?'老师':'学生'}}</p>
            </FormItem>
            <FormItem label="账号：">
                <p>{{formData.account}}</p>
            </FormItem>
            <FormItem label="工号：" v-if="formData.is_student === '0'">
                <p>{{formData.work_number}}</p>
            </FormItem>
            <FormItem label="学号：" v-else>
                <p>{{formData.number}}</p>
            </FormItem>
            <FormItem>
                <Button type="primary"  @click="modal5 = true" style="background: #f5b4ca;
            border: 1px solid #f5b4ca;" v-if="userid === formData.id">重置密码</Button>
            </FormItem>
        </Form>
        <div class="bottom">
            <Button type="primary" class="btn" @click="ok"  v-if="userid === formData.id">修改</Button>
        </div>
        <Modal
            v-model="modal5"
            title="重置密码"
            :loading="Modal5loading"
            @on-ok="pwdOk">
                <Form ref="formValidate" :model="pwdData" :rules="ruleValidate" :label-width="80">
                    <FormItem label="密码" prop="pwd">
                        <Input v-model="pwdData.pwd"  placeholder="请输入密码" type="password"></Input>
                    </FormItem>
                </Form>
        </Modal>
  </section>
</template>

<script>
  import   user  from '../../api/articles'
  import    { EventBus }  from '../../bus'
export default {
    data() { 
        return { 
            formData: {},
            show: false,
            modal5: false,
            Modal5loading: false,
            pwdData: { 
                pwd: '',
                nickname: localStorage.nickname,
                mail: localStorage.mail,
                is_student: localStorage.is_student,
                account: localStorage.account,
                work_number: localStorage.work_number,
                number: localStorage.number,
                id: localStorage.id,
                status: Number(localStorage.status),
            },
            ruleValidate: { 
                pwd: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { max: 36, min : 6 , message: '请输入6-36位数密码',}
                ],
            },
            defaultList: [],
            userid: Number(localStorage.userid)
        }
    },
    methods:{ 
        handleRemove (file) {
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: 'The file format is incorrect',
                desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: 'Exceeding file size limit',
                desc: 'File  ' + file.name + ' is too large, no more than 2M.'
            });
        },
        handleBeforeUpload () {

        },
        // 上传图片成功
        uploadSuccess({path}) {
            let srt = path.replace('/public','')
            let url = `http://127.0.0.1:3000${srt}`
            console.log(url);
            this.$set(this.formData,'img',url)
        },
        async ok() { 
            try{ 
                const { data : res } = await user.updateUser({
                    ...this.formData,
                    token: localStorage.token
                })
                if(res.code !== 200) return this.$Message.error('系统繁忙')
                this.$Message.success('修改成功')
                EventBus.$emit("getName", this.formData.nickname);
                localStorage.nickname = this.formData.nickname
                localStorage.mail = this.formData.mail
                localStorage.img = this.formData.img
                this.$router.push('/article-list')
            }catch(e) { 
                console.log(e);
            }
        },
        checkMail(e) { 
            let str = this.validateEmail(e.target.value)
            this.show = !str ? true : false
        },
        validateEmail(email) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
        },
        async pwdOk() { 
            try{
                const { data : res} = await user.updateUser({
                    ...this.pwdData
                })
                if(res.code !== 200) return this.$Message.error(res.msg);
                this.modal5 = false
                this.$Message.success('密码修改成功,请重新登录');
                localStorage.clear()
                this.$router.replace('/login')
            }catch(e) {
                console.log(e);
            }
        },
        async getInfo() { 
            try{ 
                const { data : res } = await user.userDetail({
                    id: this.$route.query.id
                })
                if(res.code !== 200) return this.$Message.error('系统繁忙')
                this.formData = res.data
            }catch(e) { 
                console.log(e);
            }
        }
    },
    created(){ 
        this.getInfo()
    },
}
</script>

<style scoped lang="less">
    .author {
        box-sizing: border-box;
        width: @window-Width;
        min-height: 77vh;
        margin: 24px auto;
        overflow: hidden;
        padding-bottom: 24px;
        background-color: #fff;
        border-radius: 6px;
        position: relative;
    }
    .item {
        width: 100%;
        padding: 48px 0;
        text-align: center;
        background: white;
    }
    .box{
        display: flex;
        align-items: center;
        padding: 20px;
        .box-font{ 
            
        }
    }
    .ipt{ 
        width: 250px;
    }
    .bottom{ 
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translate(-50%);
        padding-bottom: 50px;
        .btn{ 
            width: 250px;
            background: #f5b4ca;
            border: 1px solid #f5b4ca;
        }
    }
</style>